package Window;

import java.sql.*;
class JDBConnection {
    //Class.forName("com.mysql.cj.jdbc.Driver");
    private final String dbDrive="com.mysql.jdbc.Driver";
    private final String url = "jdbc:mysql://localhost:3306/user";
    private final String userName = "root";
    private final String password = "123456";
    private Connection con = null;
    //通过构造方法加载数据库驱动
    public JDBConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("数据库加载失败");
        }
    }
    //创建数据库连接
    public boolean creatConnection() {
        try {
            con = DriverManager.getConnection(url, userName, password);
            con.setAutoCommit(true);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            System.out.println("creatConnectionError!");
        }
        return true;
    }
    //对数据库的增加、修改和删除的操作
    public boolean executeUpdate(String sql) {
        if (con == null) {
            creatConnection();
        }
        try {
            Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
            int iCount = stmt.executeUpdate(sql);
            System.out.println("操作成功，所影响的记录数为" + String.valueOf(iCount));
            return true;
        } catch (SQLException e) {
            System.out.println("用户名已存在");
            return false;
        }
    }
    //对数据库的查询操作
    public ResultSet executeQuery(String sql) {
        ResultSet rs;
        try {
            if (con == null) {
                creatConnection();
            }
            Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
            try {
                rs = stmt.executeQuery(sql);
            } catch (SQLException e) {
                System.out.println(e.getMessage());
                return null;
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
            System.out.println("executeQueryError!");
            return null;
        }
        return rs;
    }
    //关闭数据库
    public void  closeConnection(){
        if(con==null){
            try {
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public boolean check(String name, String password) throws SQLException {
        String sql = "select * from user";
        ResultSet ret = executeQuery(sql);
        while (ret.next()) {
            if(ret.getString("name").equals(name) && ret.getString("password").equals(password)) {
                ret.close();
                return true;
            }
        }
        ret.close();
        return false;
    }
}
